<template>
  <div>
    <p class="ctrl-btn">
      <el-button type="primary" size="small" @click="saveCase">保存方案</el-button>
      <el-button type="danger" size="small" @click="delCase">删除方案</el-button>
      <el-button size="small" @click="closeCase">关闭</el-button>
    </p>
    <div class="container">
      <div class="col-one">
        <p class="s-title">组件列表</p>
        <p class="s-title-slave">*注：双击增加组件</p>
        <ul class="list-item">
          <li v-for="o in inputComponents" :key="o.type" @dblclick="addPanel(o)">
            <i :class="o.iconStyle" />
            <span>{{ o.name }}</span>
          </li>
        </ul>
      </div>
      <div class="col-two">
        <p class="s-title">预览表单</p>
        <el-form ref="form" class="custom-form" label-width="100px">
          <div v-for="d in dataFormArr" :key="d.fieldId" class="form-item">
            <div class="cli-panel" :class="d.fieldId === panelForm.fieldId ? 'cli-panel-sel':''" @click="selPanel(d)">
              <el-button class="panel-del-btn" type="danger" size="mini" icon="el-icon-delete" circle @click.stop="delPanel(d)" />
            </div>
            <el-form-item :label="d.name" style="margin-left: 15px" :required="d.isRequired === 1">
              <!-- 文本框 -->
              <el-input v-if="d.type === 'text'" v-model="d.defaultValue" />
              <!-- 选择框 -->
              <el-select v-if="d.type === 'select'" v-model="d.selected" placeholder="请选择">
                <el-option
                  v-for="(item, c) in d.options"
                  :key="c"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <!-- 数字框 -->
              <el-input-number v-if="d.type === 'number'" v-model="d.defaultValue" />
              <!-- 单选框 -->
              <el-radio-group v-if="d.type === 'radio'" v-model="d.selected">
                <el-radio v-for="(op, c) in d.options" :key="'radio' + c" :label="op.value">{{ op.label }}</el-radio>
              </el-radio-group>
              <!-- 多选框 -->
              <el-checkbox-group v-if="d.type === 'checkbox'" v-model="d.selected">
                <el-checkbox v-for="(op, c) in d.options" :key="'checkbox' + c" :label="op.value" :checked="d.checked">
                  {{ op.label }}
                </el-checkbox>
              </el-checkbox-group>
              <!-- 日期框 -->
              <div v-if="d.type === 'date'" class="block">
                <el-date-picker
                  v-model="d.defaultValue"
                  :type="d.dateType"
                  placeholder="选择日期时间"
                />
              </div>
              <!-- 上传 -->
              <el-upload
                v-if="d.type === 'upload'"
                action=""
                list-type="picture-card"
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="col-three">
        <div v-if="panelDetailFlag">
          <p class="s-title">组件属性</p>
          <el-form ref="panelForm" class="panel-form-container" :model="panelForm" label-width="80px">
            <el-form-item label="组件名称">
              <!-- 文本框 -->
              <el-input v-model="panelForm.name" maxlength="20" />
            </el-form-item>
            <el-form-item label="是否必填">
              <!-- 文本框 -->
              <el-radio v-model="panelForm.isRequired" :label="0">非必填</el-radio>
              <el-radio v-model="panelForm.isRequired" :label="1">必填项</el-radio>
            </el-form-item>
            <!-- 选项 -->
            <div v-if="['radio','select','checkbox'].includes(panelForm.type)" class="options">
              <p>
                <span>组件选项</span>
              </p>
              <div v-for="(option, i) in panelForm.options" :key="'options_'+i" class="options-item">
                <el-row>
                  <el-col :span="2" class="text-center">键</el-col>
                  <el-col :span="5">
                    <el-input v-model="option.label" maxlength="20" />
                  </el-col>
                  <el-col :span="2" class="text-center">值</el-col>
                  <el-col :span="5">
                    <el-input v-model="option.value" />
                  </el-col>
                  <el-col :span="3" class="text-center">选中</el-col>
                  <el-col :span="2">
                    <el-checkbox v-model="option.checked" @change="optionCheckedHandler(panelForm.options, i, panelForm.type === 'checkbox')" />
                  </el-col>
                  <el-col :span="5" class="text-center">
                    <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="addOptions(i)" />
                    <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="delOptions(i)" />
                  </el-col>
                </el-row>
              </div>
            </div>
            <el-form-item v-else-if="panelForm.type !== 'upload'" label="默认值">
              <el-input v-model="panelForm.defaultValue" />
            </el-form-item>
            <template v-if="panelForm.type === 'number'">
              <el-form-item label="最大值">
                <el-input v-model="panelForm.max" type="number" placeholder="请输入最大值" />
              </el-form-item>
              <el-form-item label="最小值">
                <el-input v-model="panelForm.min" type="number" placeholder="请输入最小值" />
              </el-form-item>
              <el-form-item label="精度">
                <el-input-number v-model="panelForm.digits" :min="0" :max="10" label="描述文字" />
              </el-form-item>
            </template>
            <!--            <el-form-item v-if="panelForm.type === 'upload'" label="上传类型">-->
            <!--              <el-select v-model="panelForm.uploadType" clearable placeholder="不填默认不限制">-->
            <!--                <el-option v-for="(item,i) in uploadTypeOptions" :key="i" :label="item.dictLabel" :value="item.dictValue" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item v-if="panelForm.type === 'date'" label="时间类型">
              <el-select v-model="panelForm.dateType" clearable placeholder="不填默认日期类型">
                <el-option label="日期" value="date" />
                <el-option label="时间" value="time" />
                <el-option label="日期 + 时间" value="datetime" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="panel-save-btn">
            <el-button size="mini" round @click="resetPanelForm">重置</el-button>
            <el-button type="primary" size="mini" round @click="savePanelForm">保存</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  saveCustomForm,
  delCustomForm
} from '@/api/qualityManage/checkTable'
export default {
  name: 'CustomFormVue',
  props: {
    baseData: {
      type: Object,
      default: () => ({
        visible: false,
        checktable: {},
        fieldData: []
      })
    }
  },
  data() {
    return {
      /* 属性名 */
      attrName: 'fieldData',
      /* 防报错 没有实际用途 */
      selValue: [],
      /* 控件列表 */
      inputComponents: [
        { 'name': '文本', 'type': 'text', 'isRequired': 0, 'iconStyle': 'el-icon-full-screen' },
        { 'name': '选择框', 'type': 'select', 'isRequired': 0, 'iconStyle': 'el-icon-arrow-down', 'options': [{ 'label': '选项一', 'value': '1' }], selected: '' },
        { 'name': '数字框', 'type': 'number', 'isRequired': 0, 'iconStyle': 'el-icon-circle-plus-outline' },
        { 'name': '单选框', 'type': 'radio', 'isRequired': 0, 'iconStyle': 'el-icon-aim', 'options': [{ 'label': '选项一', 'value': '1' }], selected: '' },
        { 'name': '多选框', 'type': 'checkbox', 'isRequired': 0, 'iconStyle': 'el-icon-circle-check', 'options': [{ 'label': '选项一', 'value': '1' }], selected: [] },
        { 'name': '日期选择', 'type': 'date', 'isRequired': 0, 'iconStyle': 'el-icon-date', 'dateType': 'date' },
        { 'name': '上传控件', 'type': 'upload', 'isRequired': 0, 'iconStyle': 'el-icon-upload', 'uploadType': '' }
      ],
      /* 当前工序ID */
      curChecktableId: '',
      /* 表单数据总集 */
      dataFormArr: [
        // { fieldId: '123', 'name': '文本框', 'isRequired': 0, type: 'text', options: null, defaultValue: null },
        // { fieldId: '456', 'name': '选择框', 'isRequired': 0, type: 'select', options: [{ 'label': '选项一', 'value': '1' }], defaultValue: null },
        // { fieldId: '789', 'name': '多选框', 'isRequired': 0, type: 'checkbox', options: [{ 'label': 'A', 'value': '1' }], defaultValue: [] },
        // { fieldId: '111', 'name': '日期选择', 'isRequired': 0, type: 'date', options: null, defaultValue: null, 'dateType': 'date' },
        // { fieldId: '000', 'name': '上传控件', 'isRequired': 0, type: 'upload', options: null, defaultValue: null }
      ],
      /* 组件详情表单 */
      panelForm: {
        fieldId: '',
        name: '',
        type: '',
        'isRequired': 0
      },
      /* 控制组件显示隐藏 */
      panelDetailFlag: false,
      /* 初始表单值 */
      initFormValue: null,
      /* 文件上传类型 */
      uploadTypeOptions: []
    }
  },
  watch: {
    'baseData.visible': function(val) {
      if (val) this.init()
    }
  },
  mounted() {
    this.init()
    this.getDicts('upload_type').then(response => {
      this.uploadTypeOptions = response.data
    })
  },
  methods: {
    /* 初始化 */
    init() {
      // 初始化数据信息
      if (this.baseData[this.attrName] && Array.isArray(this.baseData[this.attrName])) {
        const dataFormArr = JSON.parse(JSON.stringify(this.baseData[this.attrName]))
        dataFormArr.forEach(dataForm => {
          const options = dataForm.options
          dataForm.defaultValue = dataForm.defaultValue || undefined
          if (options && options.length > 0) {
            if (dataForm.type === 'checkbox') {
              dataForm.selected = options.filter(item => item.checked).map(item => item.value)
            } else {
              const checked = options.find(item => item.checked)
              dataForm.selected = checked ? checked.value : ''
            }
          }
        })
        this.dataFormArr = dataFormArr
      } else {
        this.dataFormArr = []
      }
      this.curChecktableId = this.baseData.checktable.fid
      this.panelDetailFlag = false
      this.$nextTick(() => {
        this.initFormValue = JSON.parse(JSON.stringify(this.dataFormArr))
      })
    },
    /* 添加组件 */
    addPanel(panel) {
      const newPanel = JSON.parse(JSON.stringify(panel))
      newPanel.fieldId = new Date().getTime()
      this.dataFormArr.push(newPanel)
    },
    /* 选择组件 */
    selPanel(panel) {
      this.panelForm = JSON.parse(JSON.stringify(panel))
      this.panelDetailFlag = true
    },
    /* 删除组件 */
    delPanel(panel) {
      const fieldId = panel.fieldId
      for (let i = 0; i < this.dataFormArr.length; i++) {
        if (fieldId === this.dataFormArr[i].fieldId) {
          this.dataFormArr.splice(i, 1)
          this.panelDetailFlag = false
          break
        }
      }
    },
    /* 添加选项 */
    addOptions(i) {
      this.panelForm.options.splice(i + 1, 0, { 'label': '', 'value': '' })
    },
    /* 删除选项 */
    delOptions(i) {
      this.panelForm.options.splice(i, 1)
    },
    optionCheckedHandler(data, index, multiple = false) {
      if (!multiple) {
        data.forEach((item, i) => {
          if (index !== i) {
            item.checked = false
          }
        })
      }
    },
    /* 重置组件表单 */
    resetPanelForm() {
      for (const panel of this.dataFormArr) {
        if (panel.fieldId === this.panelForm.fieldId) {
          this.panelForm = JSON.parse(JSON.stringify(panel))
          break
        }
      }
    },
    /* 保存组件表单 */
    savePanelForm() {
      for (let i = 0; i < this.dataFormArr.length; i++) {
        if (this.dataFormArr[i].fieldId === this.panelForm.fieldId) {
          const data = JSON.parse(JSON.stringify(this.panelForm))
          data.defaultValue = data.defaultValue || undefined
          if (data.options && data.options.length > 0) {
            if (this.panelForm.type === 'checkbox') {
              data.selected = data.options.filter(item => item.checked).map(item => item.value)
            } else {
              const checked = data.options.find(item => item.checked)
              data.selected = checked ? checked.value : ''
            }
          }
          this.$set(this.dataFormArr, i, data)
          this.$message.success('操作成功')
          break
        }
      }
    },
    /* 保存方案 */
    saveCase() {
      // 先判断方案是否有变更
      var oldData = JSON.stringify(this.initFormValue)
      var newData = JSON.stringify(this.dataFormArr)
      // console.log(oldData, newData)
      if (oldData === newData) {
        this.$message.warning('当前方案没有变更，无需保存！')
        return
      }
      // 保存方案
      var formData = JSON.parse(JSON.stringify(this.dataFormArr))
      for (const i in formData) {
        if (Array.isArray(formData[i].options)) {
          formData[i].options = JSON.stringify(formData[i].options)
        }
      }
      saveCustomForm({ fields: formData, checkTableId: this.curChecktableId }).then(request => {
        if (request.code === 200) {
          this.$message.success('保存方案成功')
          this.baseData.visible = false
        } else {
          this.$message.error('保存方案失败')
        }
      })
    },
    /* 关闭窗口 */
    closeCase() {
      this.baseData.visible = false
    },
    /* 删除方案 */
    delCase() {
      this.$confirm('是否确认删除【' + this.baseData.checktable.fnameL2 + '】的自定义方案吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delCustomForm(this.curChecktableId).then(() => {
          this.msgSuccess('删除成功')
          this.baseData.visible = false
        })
      }).catch(function() {
      })
    }
  }

}
</script>

<style scoped lang="scss">
  .ctrl-btn{
    position: absolute;
    right: 10px;
    top: 20px;
    margin: 0;
  }
  .container{
    min-height: 400px;
    display: flex;
    .col-one {
      flex: 1 1 20%;
      /*width:20%;*/
      border-right: 1px solid #999999;
    }
    .col-two {
      flex: 1 1 40%;
      width:40%;
      border-right: 1px solid #999999;
      max-height: 700px;
      overflow: auto;
    }
    .col-three {
      flex: 1 1 40%;
      width:40%;
      max-height: 700px;
      overflow: auto;
    }
    .s-title {
      font-weight: bold;
      padding-left: 10px;
      color:#333;
      margin-bottom: 20px;
      font-size: 14px;
      .panel-save-btn{
        display: inline-block;
        float: right;
      }
    }
    .s-title-slave{
      padding-left: 10px;
      font-size: 12px;
      color: darkred;
    }
  }
.list-item {
  width: 150px;
  color: #333333;
  list-style: none;
  padding: 0 10px 0 0;

  li {
    line-height: 30px;
    background: rgb(246, 247, 255);
    margin-bottom: 10px;
    padding-left: 10px;
    cursor: pointer;
    span {
      display: inline-block;
      margin-left: 10px;
    }
  }
  li:hover {
    color: white;
    background: #1c84c6;
  }
}
.form-item {
  position: relative;
  .cli-panel {
    position: absolute;
    top: -5px;
    width: 100%;
    height: calc(100% + 10px);
    z-index: 2;
    cursor: pointer;
    .panel-del-btn {
      display: none;
    }
  }
  .cli-panel:hover {
    border: 1px dashed #999999;
  }
}
.custom-form{
  margin: 0 10px 0 20px;
  width: calc(100% - 30px);
}
.options {
  p{
    width: 100px;
    padding-left: 10px;
    font-weight: bold;
    color: #666666;
  }
  .options-item{
    padding: 5px 0 5px 20px;
    line-height: 35px;
  }
}
  .cli-panel-sel{
    border: 1px dashed #1ab394 !important;
    position: relative;
    .panel-del-btn {
      position: absolute;
      top: 5px;
      left: -15px;
      display: inline-block !important;
    }
  }
  .panel-save-btn{
    width: calc(100% - 20px);
    margin-left: 20px;
    margin-top: 20px;
    padding-top: 10px;
    border-top: 1px solid #eeeeee;
    text-align: center;
  }
  .required-flag{
    position: absolute;
    top: 10px;
    left: 90px;
    color: red;
  }
</style>
